import { invokeAPi, invokeAsyncAPi, registerInformApi } from '@/xz-fn'
import { ref } from 'vue'
import { userAppStore } from '@/stores/user'

export const useRegisterMessage = () => {
  const mainID = ref(0)
  const winID = ref(0)

  const registerOb = () => {
    registerInformApi('Notify_WebMessage', (id: number, payload: any) => {
      if (id === winID.value && payload) {
        let _payload

        try {
          _payload = typeof payload === 'string' ? JSON.parse(payload) : payload
        } catch (error) {
          _payload = null
        }

        if (_payload) {
          switch (_payload.action) {
            case 'focus':
              invokeAPi('jsMsg_SetWndStatus', 6)
              break;
            default:
              break;
          }
        }
      }
    })
  }

  const getMessageID = () => {
    invokeAsyncAPi('jsMsg_GetWndInfo').then((res: any) => {
      if (res.payload) {
        const _payload = JSON.parse(res.payload)

        if (_payload.mainID) {
          mainID.value = _payload.mainID
        }
      }
    })

    invokeAsyncAPi('jsMsg_GetWndID').then((id: any) => {
      winID.value = id
    })
  }

  const registerLogin = () => {
    registerInformApi("Notify_LoginStatusChange", async (status: number) => {
      if (status === 3) {
        // 登录成功
        await userAppStore().getToken();
        if (userAppStore().token) {
          await userAppStore()
            .checkStatus()
            .catch(() => {});
        }
        if (userAppStore().token) {
          userAppStore().getUserInfo();
        }
      } else if (status === 1) {
        // 退出登录
        userAppStore().resetUserInfo(false);
      }
    });
  }

  invokeAPi("xz_page_load_finished")
  getMessageID()
  registerOb()
  registerLogin()

  return {
    mainID,
    winID
  }
}